package com.csailing4cloud.csailing.common.feign.hystrix;

import feign.hystrix.FallbackFactory;
import org.springframework.cglib.proxy.Enhancer;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

/**
 * @author
 * @param <T>
 * 默认 Fallback，避免写过多fallback类
 */
public class CsailingFeginFallbackFactory<T> implements FallbackFactory<T> {

    public static final CsailingFeginFallbackFactory INSTANCE = new CsailingFeginFallbackFactory();
    private static final ConcurrentMap<Class<?>, Object> FALLBACK_MAP = new ConcurrentHashMap<>();

    @SuppressWarnings("unchecked")
    public T create(final Class<?> type, final Throwable cause) {
        return (T) FALLBACK_MAP.computeIfAbsent(type, key -> {
            Enhancer enhancer = new Enhancer();
            enhancer.setSuperclass(key);
            enhancer.setCallback(new CsailingFeignFallbackMethod(type, cause));
            return enhancer.create();
        });
    }
    @Override
    public T create(Throwable throwable) {
        return null;
    }
}
